package xxl.robotlegs.extensions.mediatormap.impl 
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import xxl.robotlegs.extensions.mediatormap.api.IMediatorMapping;
	/**
	 * ...
	 * @author XXL
	 */
	public class MediatorManager 
	{
		private var _factory:MediatorFactory;
		
		public function MediatorManager(factory:MediatorFactory) 
		{
			_factory = factory;
		}
		
		public function addMediator(mediator:Object, item:Object, mapping:IMediatorMapping):void
		{
			const displayObject:DisplayObject = item as DisplayObject;
			if (!displayObject)
			{
				initializeMediator(mediator, item);
				return;
			}
			
			if (mapping.autoRemoveEnabled)
			{
				displayObject.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			}
			initializeMediator(mediator, displayObject);
		}
		
		public function removeMediator(mediator:Object, item:Object, mapping:IMediatorMapping):void
		{
			const displayObject:DisplayObject = item as DisplayObject;
			if (displayObject)
			{
				displayObject.removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			}
			if (mediator)
			{
				destroyMediator(mediator);
			}
		}
		
		//----------private
		
		private function initializeMediator(mediator:Object, mediatedItem:Object):void
		{
			if ("preInitialize" in mediator)
			{
				mediator.preInitialize();
			}
			
			if ("viewComponent" in mediator)
			{
				mediator.viewComponent = mediatedItem;
			}
			
			if ("initialize" in mediator)
			{
				mediator.initialize();
			}
			
			if ("postInitialize" in mediator)
			{
				mediator.postInitialize();
			}
		}
		
		private function onRemovedFromStage(event:Event):void
		{
			_factory.removeMediators(event.target);
		}
		
		private function destroyMediator(mediator:Object):void
		{
			if ("preDestroy" in mediator)
			{
				mediator.preDestroy();
			}
			if ("destroy" in mediator)
			{
				mediator.destroy();
			}
			if ("viewComponent" in mediator)
			{
				mediator.viewComponent = null;
			}
			if ("postDestroy" in mediator)
			{
				mediator.postDestroy();
			}
		}
	}

}